#!/usr/bin/env python3
# -*- coding: utf-8 -*-
########################################################################
#
# Copyright (c) 2023 Zhiyong Lin. All Rights Reserved
#
########################################################################
'''
@File    :   __main__.py
@Time    :   2025/10/20 15:13:18
@Author  :   lzy2lcy 
@Version :   1.0
@Desc    :   
'''

import argparse
import config 
from mcp.server.fastmcp import FastMCP
from utils.web_server import GunicornApplication

parser = argparse.ArgumentParser(description='MCP service')
parser.add_argument(
    '-m','--module',
    choices=['mcp'],
    default='mcp',
    help='service to start')
parser.add_argument(
    '--apitype',
    choices=['default','gunicorn'],
    default='default',
    help='api start type'
)

args = parser.parse_args()
logger = get_logger(__name__)

def run_mcp_default():
    """使用默认方式运行MCP服务"""
    mcp = FastMCP("Database MCP Server")
    mcp.run(transport="http", port=config.MCP_PORT)

def run_mcp_gunicorn():
    """使用Gunicorn运行MCP服务"""
    from gunicorn.app.base import BaseApplication
    class GunicornApplication(BaseApplication):
        def __init__(self, app, options=None):
            self.options = options or {
                'bind': '%s:%s' % (config.MCP_HOST, config.MCP_PORT),
                'workers': config.GUNICORN_WORKER_COUNT,
                'worker_class': config.GUNICORN_WORKER_CLASS
            }
            self.application = app
            super().__init__()
        
        def load_config(self):
            config = dict(
                [
                    (key, value)
                    for key, value in self.options.items()
                    if key in self.cfg.settings and value is not None
                ]
            )
            for key, value in config.items():
                self.cfg.set(key.lower(), value)
        
        def load(self):
            return self.application

    mcp = FastMCP("Database MCP Server")
    GunicornApplication(mcp, {
        'bind': '%s:%s' % (config.FLASK_HOST, config.MCP_PORT),
        'workers': config.GUNICORN_WORKER_COUNT,
        'worker_class': config.GUNICORN_WORKER_CLASS
    }).run()            

def run_mcp(apitype):
    """运行MCP服务"""
    globals()['run_mcp_%s' % apitype]()

def main():
    """主函数"""
    if args.module == 'mcp':
        run_mcp(args.apitype)

if __name__ == "__main__":
    main()

